package huawei;

import java.util.*;

/**
 * 跳马
 */
public class Q88 {

    static int[][] direction = {{1,2}, {1,-2}, {2,1}, {2, -1}, {-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}};

//    static int[][] qp = {{4,7,0,4,8},{4,7,4,4,0},{7,0,0,0,0}};
    static int[][] qp = {{4,7,0,0,0},{0,0,0,0,0},{7,0,0,0,0}};
//    static int[][] qp = {{1,0},{0,1},{0,1}};


    public static void main(String[] args) {

        List<Map<String, Integer>> allCanJumped = new ArrayList<>();

        for (int i = 0; i < qp.length; i++) {
            for (int j = 0; j < qp[i].length; j++) {
                if (qp[i][j] > 0) {
                    Map<String, Integer> jumped = new HashMap<>();
                    jump(i, j, qp[i][j], 0, jumped);
                    allCanJumped.add(jumped);
                }
            }
        }
        System.out.println(allCanJumped);

        Set<String> mergeSet = new HashSet<>(allCanJumped.get(0).keySet());
        for (int i = 1; i < allCanJumped.size(); i++) {
            mergeSet.retainAll(allCanJumped.get(i).keySet());
            if (mergeSet.isEmpty()) {
                break;
            };
        }

        System.out.println(mergeSet);
        if (mergeSet.isEmpty()) {
            System.out.println(0);
            return;
        }

        int min = Integer.MAX_VALUE;

        for (String key : mergeSet) {
            int sum = 0;
            for (int i = 0; i < allCanJumped.size(); i++) {
                sum += allCanJumped.get(i).get(key);
            }
            min = Math.min(min, sum);
        }

        System.out.println(min);
    }

    public static void  jump (int x, int y, int canJumpTotal,int jumpedCount, Map<String, Integer> jumped) {
        if (!(x >= 0 && y >= 0 && x < qp.length && y < qp[0].length)) return;
        if (jumped.containsKey(x + "_" + y)) return;
        if (canJumpTotal < jumpedCount) return;

        jumped.put(x + "_" + y, jumpedCount);

        for (int[] d : direction) {
            int newX = x + d[0];
            int newY = y + d[1];

            jump(newX, newY, canJumpTotal, jumpedCount + 1, jumped);
        }
    }


}
